<?php

declare(strict_types=1);

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\DbConnection\Db;

/**
 * 商家动态评论
 * Class MomentsReviewService
 * @package App\Service
 */
class MomentsReviewService extends BaseService
{
    const TYPE_ARTICLE_REVIEW = 1;
    const TYPE_REVIEW_REVIEW = 2;
    const TYPE_ZAN = 3;// 点赞
    const TYPE_STAR = 4;// 收藏

    /**
     * 动态评论|评论评论
     * @param array $reviewData
     * @return bool
     */
    public function review(array $reviewData): bool
    {
        $review = array_filter($reviewData, function ($fields) {
            if (!in_array($fields, ['reviewer', 'shop_id', 'review_info', 'replay_to', 'replay_time', 'review_type', 'is_author', 'moments_id', 'reviewer_ip', 'locate_tag'])) {
                return false;
            } else {
                return true;
            }
        }, ARRAY_FILTER_USE_KEY);
        // 仅处理评论
        if (!in_array($review['review_type'], [self::TYPE_ARTICLE_REVIEW, self::TYPE_REVIEW_REVIEW])) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '评论失败1');
        }
        // 回复评论
        $main_review_id = $replay_user = 0;
        if (!empty($review['replay_to'])) {
            $apply_to = $this->getModelInstance()->where(['shop_id' => $review['shop_id'], 'id' => $review['replay_to'], 'delete_time' => 0])->first();
            if (empty($apply_to)) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '该评已被删除！');
            }
            $main_review_id = $apply_to->replay_to == 0 ? $review['replay_to'] : $apply_to->main_review_id;
            $replay_user = $apply_to->reviewer;
        }

        try {
            $instance = $this->getModelInstance();
            // 主评论ID
            $instance->main_review_id = $main_review_id;
            $instance->replay_user = $replay_user;
            foreach ($review as $field => $value) {
                $instance->$field = $value;
            }
            $instance->save();
        } catch (\Throwable $exception) {
            echo $exception->getMessage();
            return false;
        }
        return true;
    }

    /**
     * 点赞|取消点赞 或者 收藏|取消收藏
     * @param int $favor_type
     * @param int $moments_id
     * @param int $user_id
     * @param int $shop_id
     * @param int $is_author 是否为作者1是 0不是
     * @param int $review_id 评论ID：为0时对象为：“商家动态”
     * @return int type:1点赞收藏 2取消点赞收藏 0错误
     */
    public function userFavorAct(int $favor_type, int $moments_id, int $user_id, int $shop_id, int $is_author = 0, int $review_id = 0): int
    {
        if (!in_array($favor_type, [self::TYPE_ZAN, self::TYPE_STAR]) || (empty($review_id) && $favor_type == self::TYPE_STAR)) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '操作有误');
        }
        // 评论ID为0：操作内容为文章
        try {
            // 是否存在点赞记录
            $instance = $this->getModelInstance()
                ->where('moments_id', '=', $moments_id)
                ->where('replay_to', '=', $review_id)
                ->where('reviewer', '=', $user_id)
                ->where('review_type', '=', $favor_type)
                ->first();
            if (empty($instance) || empty($instance->toArray())) {
                $instance = $this->getModelInstance();
                $instance->reviewer = $user_id;
                $instance->shop_id = $shop_id;
                $instance->is_author = $is_author;
                $instance->review_type = $favor_type;
                $instance->replay_to = $review_id;// 为谁点赞 0：动态 >0评论
                $instance->moments_id = $moments_id;
                $type = 1;
            } else {
                if ($instance->delete_time > 0) {
                    $type = 1;
                    $instance->delete_time = 0;
                } else {
                    $type = 2;
                    $instance->delete_time = time();
                }
            }
            // 评论点赞
            if (!empty($review_id)) {
                // 评论操作（点赞|取消点赞）
                $opt = $type == 1 ? "+1" : "-1";
                $this->getModelInstance()
                    ->where(['id' => $review_id, 'delete_time' => 0, 'shop_id' => $shop_id])
                    ->where(function ($where) use ($type) {
                        if ($type != 1) {// 取消点赞
                            $where->where('heart_num', '>', 0);
                        }
                    })
                    ->update(['heart_num' => Db::raw('heart_num' . $opt)]);
            }
            if (!$instance->save()) {
                return 0;
            } else {
                return $type;
            }
        } catch (\Throwable $exception) {
            print_r($exception->getMessage());
            return 0;
        }
    }
}